// pages/orderSheet/orderSetling.js
const util = require("../../utils/util")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: '',
    imgPath: "/images",

    //订单信息，从详情传入，从内部存储传入
    order: null,

    //已购买商品列表
    buyedList: [
    //   {
    //   itemId: 1,
    //   itemNum: 1,
    //   itemImgSrc: '/cart/item.jpg',
    //   itemName: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
    //   itemDescrition: '尺寸：L',
    //   itemPrice: '138.00',
    // }
  ],

    //5折加购商品
    listData: [
    //   {
    //   checked: false,
    //   id: '1',
    //   num: 2,
    //   imgSrc: '/cart/item.jpg',
    //   name: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
    //   descrition: '尺寸：L',
    //   price: '138.00'
    // }, {
    //   checked: false,
    //   id: '2',
    //   num: 1,
    //   imgSrc: '/cart/item.jpg',
    //   name: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
    //   descrition: '尺寸：L',
    //   price: '138.00'
    // }
  ],

    //优惠券标识
    coupon_id: '',
    //优惠券名称
    couponName: "",

    //总价
    totalTotalPrice: 0,

    //商品总价
    totalPrice: '0',
    //商品总数
    totalNum: 0,
    //运费
    freight: '0.0',

    //收货地址
    // shipAddress:{addressId:'1',consignee:'许先生',mobile:'13060695000',address:'广东省 广州市 番禺区 汉溪大道东362号粤海广场写字楼38层3807室',isDefault:true},
    shipAddress: null,
    //待选择的地址
    addressList: [{
        addressId: '1',
        consignee: '许先生',
        mobile: '13060695000',
        address: '广东省 广州市 番禺区 汉溪大道东362号粤海广场写字楼38层3807室',
        isDefault: true
      },
      {
        addressId: '2',
        consignee: '许先生2',
        mobile: '13060695000',
        address: '广东省 广州市 番禺区 汉溪大道东362号粤海广场写字楼38层3807室',
        isDefault: false
      }
    ],

    //显示选择地址对话框
    showSelAddr: false,

    //购物车下单标识
    order_from: '',

    //是否免费商品,默认不是免费
    isFreeGoods: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const util = require("../../utils/util")
    this.setData({
      imgPath: util.getImgPath()
    })

    const that = this;

    //购物车下单标识
    let order_from = options.order_from;
    // console.log("order_from", order_from)
    if (order_from) {
      this.setData({
        order_from: order_from,
      })
    }
    // console.log("this.data", this.data)

    //从本地存储中取出订单信息
    let order = wx.getStorageSync('order');
    // console.log("order", order);

    //订单信息保存到本地
    this.setData({
      order: order,
    })

    //已购买商品
    let buyedList = []
    for (let goods_info of order.goods_info) {
      //商品信息
      //let goods_info = order.goods_info[0];

      //已购买商品
      buyedList.push({
        itemId: goods_info.goods_id,
        itemNum: goods_info.buy_number,
        itemImgSrc: goods_info.goodsImages[0],
        itemName: goods_info.name,
        itemDescrition: goods_info.spec,
        itemPrice: goods_info.price,
      });
    }
    that.setData({
      buyedList: buyedList,
    })

    //5折加购
    that.data.listData = [];
  
    if (order.goods_info.length > 0) {
      let goods = order.goods_info[0];

      let spec_stock_id = goods.spec_stock_id;
      let spec_type = "0";
      let spec_size = spec_stock_id;
    

      //免费商品  
      if (goods.goods_type == 300) {
        //设置免费商品
        that.setData({
          isFreeGoods: true,
        })

        const api = require("../../api/api");
        api.goods.list({
          page: 1,
          goods_type: 400,
          spec_type: spec_type,
          spec_size: spec_size,
          success(res) {
            // console.log("免费商品，api.goods.list,res", res)

            let rows = res.data.data.rows;

            for (let row of rows) {
              /*
              listData: [{
                checked: false,
                id: '1',
                num: 2,
                imgSrc: '/cart/item.jpg',
                name: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
                descrition: '尺寸：L',
                price: '138.00'
              }]
              */
              that.data.listData.push({
                checked: false,
                id: row.goods_id,
                num: 1,
                imgSrc: row.image,
                name: row.goods_name,
                descrition: '',
                price: row.price,
                original_price: row.original_price,
                //spec_stock_id: goods.spec_stock_id,
                spec_stock_id: row.goods_type_specs[0].childs[0].spce_value_id,
              });
             // console.log('rowrow',row.goods_type_specs[0].childs[0].spce_value_id);
            }
         
         //  return;
            that.setData({
              listData: that.data.listData,
            })
            // console.log("that.data", that.data)
          }
        })
      }
    }


    //优惠券
    that.setData({
      couponName: order.couponName,
      coupon_id: order.coupon_id,
    })

    // console.log("this.data", this.data);

    //测试数据
    // this.data.buyedList[0].itemImgSrc=this.data.imgPath+ '/cart/item.jpg';
    // this.setData({
    //   buyedList: this.data.buyedList
    // })
    // console.log("this.data",this.data)

    //运费
    //免费数量
    this.data.freight = 0;
    for (const item of order.goods_info) {
      if (item.goods_type == 300) {
        this.data.freight += Number(item.buy_number)  * Number(item.transportation_fee);
      } else {
        let transportation_fee = 0;
        if (item.transportation_fee) transportation_fee = transportation_fee;
        this.data.freight += Number(transportation_fee);
      }
    }
    this.setData({
      freight: Number(this.data.freight).toFixed(2),
    })

    //计算汇总
    this.calTotal();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onTabbarChange(event) {
    // console.log("onTabbarChange,event", event)
    this.setData({
      active: event.detail
    })
  },
  addAddr() {
    // wx.showToast({
    //   title: '添加收货地址',
    // })
    // this.setData({
    //   showSelAddr: true
    // })

    const that = this;

    //改用微信的收货地址
    wx.chooseAddress({
      success(res) {
        // console.log(res.userName)
        // console.log(res.postalCode)
        // console.log(res.provinceName)
        // console.log(res.cityName)
        // console.log(res.countyName)
        // console.log(res.detailInfo)
        // console.log(res.nationalCode)
        // console.log(res.telNumber)

        //<shipping-address-for-selected 
        //addressId="{{shipAddress.addressId}}" 
        //consignee="{{shipAddress.consignee}}" 
        //mobile="{{shipAddress.mobile}}" 
        //address="{{shipAddress.address}}" 
        //isDefault="{{shipAddress.isDefault}}" 
        //bindtap="addAddr"/>

        let shipAddress = {
          addressId: '',
          consignee: res.userName,
          mobile: res.telNumber,
          address: res.provinceName + " " + res.cityName + " " + res.countyName + " " + res.detailInfo,
          isDefault: false
        };
        that.setData({
          shipAddress: shipAddress
        })
      },
      fail(res) {
        console.log("chooseAddress,fail,res", res)
      },
      complete(res) {
        console.log("chooseAddress,complete,res", res)
      }
    })
  },
  /**
   * 合计
   */
  calTotal() {
    this.data.totalNum = 0;
    this.data.totalPrice = 0.0;
   // console.log("this.data.buyedList", this.data.buyedList)
    //已选中的单
    for (let item of this.data.buyedList) {
      this.data.totalNum += Number(item.itemNum);
      this.data.totalPrice += Number(item.itemPrice) * Number(item.itemNum);
    }


    //加上五拆加购
    for (let item of this.data.listData) {
      if (item.checked) {
        this.data.totalNum += item.num;
        this.data.totalPrice += Number(item.price) * Number(item.num);
      }
    }


    //运费
    this.data.totalTotalPrice = this.data.totalPrice + Number(this.data.freight ? this.data.freight : 0);

    //减去优惠金额
    this.data.totalTotalPrice -= Number(this.data.order.couponPrice ? this.data.order.couponPrice : 0);
    // console.log("this.data.totalPrice",this.data.totalPrice)
    // console.log("this.data.totalTotalPrice",this.data.totalTotalPrice)

    this.setData({
      totalPrice: this.data.totalPrice,
      totalNum: this.data.totalNum,
      totalTotalPrice: Number(this.data.totalTotalPrice).toFixed(2),
    })
  },
  itemChecked(e) {
    for (let item of this.data.listData) {
      if (item.id == e.detail.id) {
        item.checked = e.detail.checked
      }
    }
    this.setData({
      listData: this.data.listData
    })

    this.calTotal();
  },
  onNumChange(e) {
    for (let item of this.data.listData) {
      if (item.id == e.detail.id) {
        item.num = e.detail.num
      }
    }
    this.setData({
      listData: this.data.listData
    })

    this.calTotal();
  },
  onSelAddrClose(e) {
    this.setData({
      showSelAddr: false
    })
  },
  /**
   * 选择地址项
   */
  onAddrItemClick(e) {
   // console.log("onAddrItemClick", e)
    this.setData({
      shipAddress: e.detail,
      showSelAddr: false
    })
   // console.log("this.data", this.data)
  },
  /**
   * 立即支付
   */
  payNow() {
    const that = this;

    if (!this.data.shipAddress) {
      wx.showToast({
        title: '请先选择地址',
        icon: 'none',
      })
      return;
    }

    wx.showModal({
      title: '立即支付',
      content: '确定立即支付该订单么？',
      complete: (res) => {
        //取消
        if (res.cancel) {

        }
        //确定
        if (res.confirm) {
          /*
          let shipAddress = {
          addressId: '',
          consignee: res.userName,
          mobile: res.telNumber,
          address: res.detailInfo,
          isDefault: false
        };
          */
        //  console.log("that.data", that.data)
          //收货地址
          let receive_info = {
            receive_address: that.data.shipAddress.address,
            receive_mobile: that.data.shipAddress.mobile,
            receive_name: that.data.shipAddress.consignee,
          }

          //商品信息
          let goods_info = [];
          for (let item of that.data.order.goods_info) {

              let goods = that.data.order.goods_info[0];
              if(goods.goods_type == 300){
                goods_info.push({
                  goods_id: item.goods_id,
                  buy_number: item.buy_number * 4,
                  spec_stock_id: item.spec_stock_id,
                });
              }else{
                goods_info.push({
                  goods_id: item.goods_id,
                  buy_number: item.buy_number,
                  spec_stock_id: item.spec_stock_id,
                });
              }

          }

          //5折加购
          for (const item of that.data.listData) {
            if (item.checked) {
              //只取尺码
              let s = item.spec_stock_id;
              
              // let sa = s.split(",");
              // let spec_stock_id = "";
              // if (sa.length > 1) {
              //   spec_stock_id = sa[1];
              // }

              goods_info.push({
                goods_id: item.id,
                buy_number: item.num,
                spec_stock_id: s,
              });
            }
          }
         // console.log("goods_info", that.data.listData)
       // return;
          //下单
          const api = require("../../api/api");
          api.order.transactions({
            goods_info: goods_info,
            //总价格
            price: that.data.totalTotalPrice,
            //收货信息
            receive_info: receive_info,
            //优惠券标识
            // coupon_id: that.data.order.coupon_id,
            coupon_id: that.data.order.coupon_id,
            channel: util.getChannel(),
            //下单标识，购物车：cart_info 
            order_from: that.data.order_from ? that.data.order_from : '',
            success(res) {
             // console.log("transactions,res", res);

              //出错
              if (res.data.code != 0) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                })
                return;
              }

              //支付
              let order_sn = res.data.data.order_sn;
              api.order.payment({
                order_sn: order_sn,
                pay_type: 'wx',
                pay_client: 'lite',
                success(resPayment) {
                  console.log("payment,resPayment", resPayment)

                  if (resPayment.data.code != 0) {
                    wx.showToast({
                      title: resPayment.data.msg,
                      icon: 'none'
                    })
                    return;
                  }

                  let dataPayment = resPayment.data.data;

                  //如果data=="success"，不再发起支付
                  if (dataPayment == "success") {
                    wx.showToast({
                      title: '订单已完成',
                    })

                    wx.navigateTo({
                      url: '/pages/orderSheet/myOrderSheet',
                    })

                    return;
                  }

                  //微信支付
                  wx.requestPayment({
                    timeStamp: dataPayment.timeStamp,
                    nonceStr: dataPayment.nonceStr,
                    package: dataPayment.package,
                    signType: 'MD5',
                    paySign: dataPayment.paySign,
                    success(resPay) {
                      console.log("wx.requestPayment,resPay", resPay)

                      wx.navigateTo({
                        url: '/pages/orderSheet/paySuccess',
                      })
                    },
                    fail(resPay) {
                      console.log("wx.requestPayment,resPay", resPay)

                      wx.navigateTo({
                        url: '/pages/orderSheet/payFail',
                      })
                    }
                  })
                }
              })
            }
          })
        }
      }
    })

  }
})